<template>
	<view>
		<tui-list-view>
			<kmlc-form-input label="小组名称" placeholder="请为小组取一个名字" show-type="edit" v-model="pageData.GroupName"></kmlc-form-input>
		</tui-list-view>

		<tui-list-view>
			<kmlc-form-switch label="是否置顶" showType="edit" v-model="pageData.TopSetting"></kmlc-form-switch>
		</tui-list-view>

		<tui-list-view>
			<kmlc-form-select-user label="小组成员" show-type="edit" select-type="multiple" v-model="pageData.Users"></kmlc-form-select-user>
		</tui-list-view>

	</view>
</template>

<script>
	import {
		PushMsg,
		DB,
		user,
		tools,
		interFace,
		test
	} from '@/common/framework';
	import moment from 'moment';
	export default {
		data() {
			return {
				curUserInfo: {},
				pushMsg:PushMsg.init(),
				pageData: {
					GroupName: "",
					TopSetting: false,
					Users: []
				}
			}
		},
		onLoad() {
			this.curUserInfo = user.getUserInfo();
			let model={
				avatar:this.curUserInfo.headerImg,
				id:this.curUserInfo.userId,
				key:this.curUserInfo.userId,
				label:this.curUserInfo.orgName,
				title:this.curUserInfo.userRealName,
				type:'user'
			};
			this.pageData.Users.push(model);
			this.$set(this.pageData.Users,0,model);
			
		},
		onNavigationBarButtonTap() {
			this.createGroup();
		},
		methods: {
			async createGroup() {
				try {
			
					let inter = interFace.getInterface();
					uni.showLoading();
					let userIds = [];
					this.pageData.Users.forEach(item => {
						if(item.type=='user'){
							userIds.push(item.id);
						}
					});
				
					let groupInfo = await this.pushMsg.createGroup(this.pageData.GroupName, this.curUserInfo.userId, userIds);
					
					uni.hideLoading();
					if (groupInfo) {
						if (this.pageData.TopSetting) {
							let t_id = tools.SHA1(groupInfo.id + this.curUserInfo.userId);
							await this.pushMsg.setTopicIsTop(t_id, 1);
						}
						await this.sendNoticeToGroupMember(groupInfo);
						inter.openUserMsgWin(groupInfo.id, groupInfo.name, groupInfo.icon, this.curUserInfo.userId, 10, 'group');
					}


				} catch (err) {
					uni.hideLoading();
					console.error(err);
				}

				
			},
			async sendNoticeToGroupMember(groupInfo) {
			
				let names = [];
				groupInfo.members.map(function(item) {
					names.push(item.name);
				});
				let msgText = groupInfo.createBy.name + " 邀请 " + names.join(',') + " 加入 " + groupInfo.name;
				let preload = {
					type: 13,
					label: 21,
					text: msgText
				};
				console.log(preload);
				await this.pushMsg.sendMsgToGroup(this.curUserInfo.userId, groupInfo.id, preload);
			}
		}
	}
</script>

<style>
</style>
